<template>
  <el-dialog
    :model-value="modelValue"
    @update:model-value="changeModelValue"
    title="商品类目"
    width="650px"
    draggable
    :close-on-click-modal="false"
    @close="resetFields"
  >
    <el-form ref="formInstance" :model="form" :rules="rules" label-width="auto">
      <el-form-item label="类目名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入商品类型名称" maxlength="30" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="类目备注" prop="memo">
        <el-input
          type="textarea"
          :autosize="{ minRows: 2 }"
          v-model="form.memo"
          placeholder="请输入商品类型备注"
          maxlength="300" show-word-limit
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeModel">取 消</el-button>
        <el-button type="primary" @click="confirm"> 提 交 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
  import { ref, watch } from 'vue';
  import { addType, updateType } from '@/server/type';
  import { ElMessage } from 'element-plus';

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    info: {
      type: Object,
      default: () => ({}),
    },
  });
  const emit = defineEmits(['update:modelValue', 'callback']);
  const formInstance = ref();
  const form = ref({});
  const rules = ref({
    name: [{ required: true, message: '请输入商品类型名称', trigger: 'blur' }],
  });

  watch(
    () => props.modelValue,
    v => {
      if (v) {
        form.value = { ...props.info };
      }
    },
  );

  function changeModelValue(v) {
    emit('update:modelValue', v);
  }

  function closeModel() {
    changeModelValue(false);
  }

  function confirm() {
    formInstance.value.validate(vaild => {
      if (vaild) {
        submit();
      } else {
        return false;
      }
    });
  }

  /**重置表单校验 */
  function resetFields() {
    formInstance.value.resetFields();
  }

  async function submit() {
    const data = { ...form.value };
    const callback = props.info.id ? updateType : addType;
    const res = await callback(data);
    if (res.code == 200) {
      ElMessage.success('操作成功');
      closeModel();
      emit('callback');
    }
  }
</script>

<style lang="scss" scoped></style>
